import React from 'react';
import './index.css'
// 左边 边界
// import ruleWin from '../../../node-game/webcocket/ruleWin.js'
import { Modal, Button, WhiteSpace, WingBlank, Toast } from 'antd-mobile';
import whiteImg from '../assets/images/write.png';
import blackImg from '../assets/images/black.png';
import defultImg from '../assets/images/defult.png';
const alert = Modal.alert;


const ws = new WebSocket('ws://192.168.44.254:8887')
//  const ws = new WebSocket('ws://localhost:8887')

// 监听这个连接
ws.onopen = () => {
    console.log('连接成功')
}


// 监听服务端发来的消息


// 点击发送消息
//  ws.send(val)

// 监听服务端的断开
ws.onclose = () => {
    console.log('服务关闭了')
}
export default class Game extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            nextPlay: "black",
            chessboard: new Array(225).fill(null),
            nextPlayId: "",
            canPlay: false,
            clients: [],
            plays: [],
            player: {
                id: "",
                ip: "",
                isReady: "",
                status: ""
            },
            activeIndex: null,
            otherPlayer: null,
            isPlayer: false
        }

    }
    init = () => {
        ws.send(JSON.stringify({
            status: this.state.player.status,
            type: "again",
            id: this.state.player.id
        }))
        Toast.info("请等待对手同意");
    }
    onLister = () => {


        ws.onmessage = (msg) => {
            const res = JSON.parse(msg.data)
            console.log(res, res.id)
            const { playState, id, isPlayer, nextPlay, nextPlayId, chessboard, winner, index, clients, plays, isOne, overReady, status, type, testList } = res
            switch (playState) {
                case 1:
                    if (isPlayer) {  //当玩家连接时
                        if (isOne) {
                            console.log(plays, id)
                            let player = plays.find(item => item.id == id);
                            this.setState({
                                player,
                                isPlayer
                            })
                        } else {
                            let otherPlayer = plays.find(item => item.id != this.state.player.id)
                            this.setState({
                                clients,
                                plays,
                                otherPlayer
                            })
                        }
                    } else {  //当观众连接时
                        console.log(res,chessboard,"data")
                        this.setState({
                            isPlayer,
                            plays,
                            player: plays[0],
                            otherPlayer: plays[1],
                            chessboard,
                            nextPlayId,
                            nextPlay
                        })
                    }

                    break;
                case 2:  //玩家准备时
                    let player = plays.find(item => item.id == this.state.player.id);
                    let otherPlayer = plays.find(item => item.id != this.state.player.id);

                    this.setState({
                        player,
                        clients,
                        plays,
                        otherPlayer
                    })
                    if (overReady) {
                        this.setState({
                            nextPlayId,
                            chessboard: new Array(225).fill(null)
                        })
                        this.allReady()
                    }
                    if (this.state.isPlayer && nextPlayId == this.state.player.id) {
                        this.setState({
                            canPlay: true
                        })
                    }
                    break;
                case 3:
                    if (winner) {
                        alert(`恭喜${winner}胜利`)

                        this.setState({
                            canPlay: false
                        })
                    }
                    let arr = JSON.parse(JSON.stringify(this.state.chessboard));
                    arr[index] = status;
                    this.setState({
                        nextPlayId,
                        nextPlay,
                        chessboard: arr,
                        activeIndex: index
                    })
                    if (this.state.isPlayer && nextPlayId == this.state.player.id) {
                        this.setState({
                            canPlay: true
                        })
                    }
                    break;
                case 4:
                    if (this.state.isPlayer) {
                        this.againPlay();
                    } else {
                        Toast.info(`${status}请求再来一次,等待对手同意`)
                    }

                    break;
                case 5:

                    if (type == "no") {
                        if (this.state.isPlayer) {
                            alert(`你得请求已被拒绝`)
                        } else {
                            Toast.info(`请求已被拒绝`)
                        }
                        break;
                    } else {
                        Toast.info(`对方同意,即将重新开始`)
                        break;
                    }
                case 6:
                    this.setState({
                        player: plays[0],
                        otherPlayer: null,
                        nextPlayId,
                        nextPlay,
                        plays
                    })
                    if (this.state.isPlayer) {
                        alert(`对手已退出游戏`)
                    }else{
                        Toast.info('玩家已退出游戏,请等待新玩家加入')
                    }
                    break;
            }

            // playState:1,  //游戏是否开始
            // ip,  //用户ip
            // id, //用户id
            // status, //用户棋色
            // nextPlay, //下一步走棋棋色
            // nextPlayId, //下一步走棋的用户id
            // client
        }
    }
    againPlay = () => {
        const okBack = () => {
            ws.send(JSON.stringify({
                type: "againOk",
                id: this.state.player.id
            }))
        }
        const cancelBack = () => {
            ws.send(JSON.stringify({
                type: "againNo",
                id: this.state.player.id
            }))
        }
        alert(`对方请求再来一次`, "", [{ text: "拒绝", onPress: cancelBack }, { text: "同意", onPress: okBack }])
    }
    onlyOne = () => {
        Toast.info('当前没有对手,请稍等', 3);
    }
    allReady = () => {
        Toast.info('现在开始', 3);
    }
    componentDidMount() {
        this.onLister()
    }
    componentWillUnmount() {

    }

    palyChess = (index) => {
        if (!this.state.canPlay || !this.state.isPlayer) return

        const { chessboard, nextPlay, nextPlayId, player } = this.state
        if (nextPlayId != player.id) {
            Toast.info(`当前为${nextPlay}走棋`)
            return false
        }

        if (chessboard[index]) return false
        const array = chessboard
        array[index] = player.status == "white" ? "white" : "black"
        // this.checkWinner(index)
        this.setState({
            nextPlay: player.status == "white" ? "black" : "white",
            chessboard: array,
            canPlay: false
        })
        ws.send(JSON.stringify({
            index,
            id: player.id,
            status: player.status,
            type: "playing"
        }))
    }
    clickReady = () => {
        const { isPlayer, player } = this.state
        if (!isPlayer) return
        ws.send(JSON.stringify({
            type: "ready", //用户准备
            id: player.id,
            isReady: true
        }))
    }
    // onClose = key => () => {
    //     this.setState({
    //       [key]: false,
    //     });
    //   }
    // checkWinner(index) {
    //     const { chessboard } = this.state
    //     if (ruleWin(chessboard, index)) {
    //         alert(chessboard[index] + " win!!!")
    //     }

    // }
    render() {
        const { ip, id, isReady, status } = this.state.player
        const otherPlayer = this.state.otherPlayer
        return (
            <div>
                <div className="nowPlayer">当前玩家:{this.state.nextPlay}</div>
                <div className="contnet">
                    <div className="player1 player">
                        {!status && <img src={defultImg} alt="" />}
                        {status == "white" && <img src={whiteImg} alt="" />}
                        {status == "black" && <img src={blackImg} alt="" />}
                        <div style={{ marginTop: "10px" }} className="address">{ip}</div>
                        <div style={{ marginTop: "10px" }} className="address">{id}</div>
                        {status && <div style={{ marginTop: "10px" }} className="address">{status == "white" ? "白棋" : "黑棋"}</div>}

                        {this.state.isPlayer && <Button onClick={this.clickReady} disabled={isReady}>{isReady ? "已准备" : "准备"}</Button>}
                        {!this.state.isPlayer && <Button disabled>{isReady ? "已准备" : "准备"}</Button>}
                    </div>
                    <div className="checkerboard">
                        {this.state.chessboard.map((item, index) => {
                            return <div className="cell" key={index}>
                                <div className={`piece ${item} ${this.state.activeIndex === index ? 'activeIndex' : ''}`} onClick={() => this.palyChess(index)}></div>
                            </div>
                        })}
                        {this.state.isPlayer && <Button className="startGame" onClick={this.init}>再来一次</Button>}

                    </div>
                    <div>
                        {otherPlayer && <div className="player2 player">
                            {!otherPlayer.status && <img src={defultImg} alt="" />}
                            {otherPlayer.status == "white" && <img src={whiteImg} alt="" />}
                            {otherPlayer.status == "black" && <img src={blackImg} alt="" />}
                            <div style={{ marginTop: "10px" }} className="address">{otherPlayer.ip}</div>
                            <div style={{ marginTop: "10px" }} className="address">{otherPlayer.id}</div>
                            {otherPlayer.status && <div style={{ marginTop: "10px" }} className="address">{otherPlayer.status == "white" ? "白棋" : "黑棋"}</div>}
                            <Button disabled>{otherPlayer.isReady ? "已准备" : "准备"}</Button>
                        </div>}
                    </div>

                </div>

                {/* <Modal
                    visible={this.state.modal1}
                    transparent
                    maskClosable={false}
                    onClose={this.onClose('modal1')}
                    footer={[{ text: 'Ok', onPress: () => { console.log('ok'); this.onClose('modal1')(); } }]}
                    wrapProps={{ onTouchStart: this.onWrapTouchStart }}
                    afterClose={() => { alert('afterClose'); }}
                >
                    <div style={{ height: 100, overflow: 'scroll' }}>
                       啊啊啊啊啊
                    </div>
                </Modal> */}

            </div>

        )
    }
}